package com.bang.study.nio.socket;

import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @ClassName: TestPipe
 * @author: BANG
 * @Date: 2019/11/12 17:25
 * @Version: 1.0
 * @Modified By:
 * @Desc: TODO
 */
public class TestPipe {

    public static void main(String[] args) throws IOException, InterruptedException {

        Pipe open = Pipe.open();
        ByteBuffer buf = ByteBuffer.allocate(1024);
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(1);


        executorService.execute(() -> {
            Pipe.SinkChannel sinkChannel = open.sink();
            //2. 将缓冲区中的数据写入管道

            buf.put("通过单向管道发送数据".getBytes());
            buf.flip();
            try {
                semaphore.acquire();
                sinkChannel.write(buf);
                semaphore.release();
                sinkChannel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        });


        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    semaphore.acquire();
                    Pipe.SourceChannel sourceChannel = open.source();
                    //3. 读取缓冲区中的数据
                    buf.flip();
                    int len = sourceChannel.read(buf);
                    System.out.println(new String(buf.array(), 0, len));
                    sourceChannel.close();
                    semaphore.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.shutdown();


    }

    @Test
    public void test1() throws Exception {
        //1. 获取管道
        Pipe pipe = Pipe.open();

        //2. 将缓冲区中的数据写入管道
        ByteBuffer buf = ByteBuffer.allocate(1024);

        Pipe.SinkChannel sinkChannel = pipe.sink();
        buf.put("通过单向管道发送数据".getBytes());
        buf.flip();
        sinkChannel.write(buf);

        //3. 读取缓冲区中的数据
        Pipe.SourceChannel sourceChannel = pipe.source();
        buf.flip();
        int len = sourceChannel.read(buf);
        System.out.println(new String(buf.array(), 0, len));

        sourceChannel.close();
        sinkChannel.close();
    }
}
